import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SessionService } from '../../../service/session.service';
import { WinForward, WinForwardConfigService } from '../../../service/config.service';

@Component({
  selector: 'app-win-forward',
  templateUrl: './win-forward.component.html',
  styleUrls: ['./win-forward.component.css']
})
export class WinForwardComponent implements OnInit {

  winForwardList: WinForward[];
  editCache = [];
  isSpinning = false;
  constructor(private message: NzMessageService, private forwardService: WinForwardConfigService, protected sessionService: SessionService) { }

  ngOnInit(): void {
    this.winForwardList = this.forwardService.getConfig();
    this.editCache = [...this.winForwardList];
  }

  winIpSortFn = (a: any, b: any) => a.winip.localeCompare(b.winip);

  startEdit(id): void {
    this.editCache[id].edit = true;
    this.editCache[id].add = false;
  }
  cancelEdit(id): void {
    this.editCache[id].edit = false;
    if (this.editCache[id].add) {
      this.delete(id);
    }
  }
  saveEdit(id): void {
    if (!this.editCache[id].winip.trim()
      || !this.editCache[id].winuser.trim()
      || !this.editCache[id].winpass.trim()
      || !this.editCache[id].winport.trim()
      || !this.editCache[id].ip.trim()
      || !this.editCache[id].port.trim()) {
      this.message.create("error", "Parameter can't be blank!!");
      return;
    }
    this.editCache[id].edit = false;
    this.winForwardList[id] = { ...this.editCache[id] };
    this.forwardService.setConfig(this.winForwardList);
    this.forwardService.saveConfig();
  }
  add() {
    let tmp: any = {
      winip: '',
      winuser: 'administrator',
      winpass: '',
      winport: '',
      ip: '',
      port: '',
      edit: true,
      add: true
    }
    this.editCache.push(tmp);
    this.winForwardList.push(tmp);
    this.winForwardList = [...this.winForwardList];
  }
  delete(id) {
    this.editCache.splice(id, 1);
    this.winForwardList.splice(id, 1);
    this.winForwardList = [...this.winForwardList];
    this.forwardService.setConfig(this.winForwardList);
    this.forwardService.saveConfig();
  }
  startForward(id) {
    this.isSpinning = true;
    this.sessionService.localSession.forwardByWindows(this.winForwardList[id]).then(() => { this.isSpinning = false; });
  }
}
